package com.wn.search.repository

import com.wn.common.model.ArticleList
import com.wn.common.model.HotSearch
import com.wn.network.api.ApiInterface
import com.wn.network.repository.BaseRepository
import dagger.hilt.android.scopes.ViewModelScoped
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject

/**
 * @Author: wn
 * @Date: 2024/12/18 16:55
 * @Description: 搜索页仓库
 */
@ViewModelScoped
class SearchRepository @Inject constructor(private val api: ApiInterface) : BaseRepository() {
  /**
   * 搜索热词
   * @param scope CoroutineScope
   * @param errorCall Function2<Int?, String?, Unit>?
   * @param showLoading Function1<Boolean, Unit>?
   * @return StateFlow<MutableList<HotSearch>?>
   */
  fun getHotSearchData(
    scope: CoroutineScope,
    errorCall: ((Int?, String?) -> Unit)? = null,
    showLoading: ((Boolean) -> Unit)? = null,
  ): StateFlow<MutableList<HotSearch>?> = callStateFlow(scope, errorCall, showLoading) {
    api.getHotSearchData()
  }

  /**
   * 搜索结果
   * @param scope CoroutineScope
   * @param errorCall Function2<Int?, String?, Unit>?
   * @param showLoading Function1<Boolean, Unit>?
   * @param page Int                                --  页码
   * @param keyWord String                          --  关键词，支持多个，空格分开
   * @return StateFlow<ArticleList?>
   */
  fun searchResult(
    scope: CoroutineScope,
    errorCall: ((Int?, String?) -> Unit)? = null,
    showLoading: ((Boolean) -> Unit)? = null,
    page: Int,
    keyWord: String,
  ): StateFlow<ArticleList?> = callStateFlow(scope, errorCall, showLoading) {
    api.searchResult(page, keyWord)
  }

  /**
   * 收藏 or 取消收藏站内文章
   * @param scope CoroutineScope
   * @param errorCall Function2<Int?, String?, Unit>?
   * @param showLoading Function1<Boolean, Unit>?
   * @param id Int                                      -- 文章 id
   * @param isCollect Boolean                           -- 是否收藏
   * @return StateFlow<Any?>
   */
  fun collectArticle(
    scope: CoroutineScope,
    errorCall: ((Int?, String?) -> Unit)? = null,
    showLoading: ((Boolean) -> Unit)? = null,
    id: Int,
    isCollect: Boolean,
  ): StateFlow<Any?> = callStateFlow(scope, errorCall, showLoading) {
    if (isCollect) {
      // 取消收藏站内文章
      api.cancelCollectArticle(id)
    } else {
      // 收藏站内文章
      api.collectArticle(id)
    }
  }
}